package com.archgeek.java.udp.v1simple;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 相当与客户端,搜索方
 *
 * @author pizhihui
 * @date 2023-03-03
 */
public class UDPSearcher {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            // 监听的 20000 端口
            ds = new DatagramSocket();

            // 发送数据
            String sendData = "Hello World!";
            byte[] sendDataByte = sendData.getBytes();
            DatagramPacket requestPacket = new DatagramPacket(sendDataByte, sendDataByte.length);
            requestPacket.setAddress(InetAddress.getLocalHost());
            requestPacket.setPort(20000);

            System.out.println("UDPSearcher send data.....");
            ds.send(requestPacket);

            // 接收服务端返回的数据
            final byte[] buf = new byte[512];
            DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
            // 接收消息
            System.out.println("UDPSearcher waiting msg......");
            ds.receive(receivePack);
            System.out.println("UDPSearcher received msg......receivePack=" + receivePack);

            String ip = receivePack.getAddress().getHostAddress();
            int port = receivePack.getPort();
            int dataLen = receivePack.getLength();
            String data = new String(receivePack.getData(), 0, dataLen);
            System.out.println("UDPSearcher receive from ip: " + ip + ",port:" + port + ",data:" + data);

            System.out.println("UDPSearcher Finished!");
        } catch (SocketException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (null != ds) {
                ds.close();
            }
        }
    }



}
